import { existsSync,writeFileSync,readFileSync,unlinkSync } from "fs";

function gettoken():string {
    return Date.now().toString()+Math.round(Math.random()*9999).toString()+Math.round(Math.random()*9999).toString()+Math.round(Math.random()*9999).toString()
}

var root = 'session/files';
export function sessionCreate(timeout_second:number=60*60*2) {
    let token=gettoken()
    let abspath = root + "/" + token + ".json"
    while (true) {
        if (existsSync(abspath)) {
            //找出真实不存在的token名称
            token=gettoken()
        } else {
            break
        }
    }
    if (!existsSync(abspath)) {
        writeFileSync(abspath, JSON.stringify({
            expaire:Date.now()+timeout_second*1000
        }))
    }
    return token
}
export function sessionGet(token:string,key:string) {
    let root = 'session/files';
    let abspath = root + "/" + token+".json"
    if (!existsSync(abspath)) {
        return null
    }
    let jsondata = JSON.parse(readFileSync(abspath).toString())
    if (jsondata['expaire'] < Date.now()) {
        unlinkSync(abspath)
        return null
    }
    return jsondata[key]
}
export function sessionSet(token:string,key:string,val:any) {
    let root = 'session/files';
    let abspath = root + "/" + token+".json"
    if (!existsSync(abspath)) {
        return null
    }
    let jsondata = JSON.parse(readFileSync(abspath).toString())
    if (jsondata['expaire'] < Date.now()) {
        unlinkSync(abspath)
        return null
    }
    jsondata[key] = val
    writeFileSync(abspath, JSON.stringify(jsondata))
}